<template>
  <a-select
    ref="select"
    v-model:value="id"
    show-search
    option-filter-prop="label"
    :allow-clear="allowClear"
    :get-popup-container="triggerNode => triggerNode.parentNode"
    :disabled="disabled"
    option-label-prop="label"
    @change="handleChange">
    <a-select-option v-for="item in dict.countriesOrRegions" :key="item.value" :label="item.text">
      <a-space><e-flag v-if="showFlag" :code="item.value" size="small" />{{ item.text }}</a-space>
    </a-select-option>
  </a-select>
</template>

<script setup>
import EFlag from '@/components/EFlag.vue'
import { useStore } from 'vuex'
import { computed, ref, watch } from 'vue'
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: 0
  },
  showFlag: {
    type: Boolean,
    default: true
  },
  allowClear: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const id = ref(props.modelValue)
watch(
  () => props.modelValue,
  value => (id.value = value)
)
const store = useStore()
const dict = ref(computed(() => store.state.dict))
store.dispatch('dict/getCountriesOrRegions').then(() => {
  if (!props.allowClear && id.value === 0) {
    id.value = dict.value.countriesOrRegions[0].value
    emits('update:modelValue', id.value)
  }
})
const emits = defineEmits(['update:modelValue'])
const handleChange = value => {
  if (typeof value === 'undefined') value = ''
  emits('update:modelValue', value)
}
</script>

<style lang="less" scoped></style>
